package com.xiongjie;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.font.FontProvider;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.region.Region;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.multipart.MultipartForm;
import io.vertx.ext.web.templ.pebble.PebbleTemplateEngine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Properties;

public class VertxPebbleTemplate {

    private static String BASEURI="src/main/resources/";
    private static String secretid;
    private static String secretkey;
    private static String region;
    private static String savebucketname;
    private static COSClient cosclient;

    public static void main(String[] args) {
//        hello();

        convertTemplateToPDFAndUploadCos("demo",new JsonObject().put("name","xiongjie"));
    }

    public static void hello(){
        Vertx vertx=Vertx.vertx();
        PebbleTemplateEngine engine=PebbleTemplateEngine.create(vertx);

        System.out.println("待查找的模版后缀默认是.peb");
        engine.render(new JsonObject().put("name","xiongjie"),"home",ar ->{
            System.out.println(ar.result());
        });

        System.out.println("等待模版渲染结束，然后继续向下执行");
        System.out.println("模版参数可以使用RoutingContext进行传递");
    }

    public static void convertTemplateToPDFAndUploadCos(String templateName,JsonObject jsonObject){
        //1.渲染模版
        Vertx vertx=Vertx.vertx();
        PebbleTemplateEngine engine=PebbleTemplateEngine.create(vertx);

        engine.render(jsonObject,templateName,res ->{
            String html=res.result().toString();
            System.out.println(html);


            //2.转化为pdf
            String pdfName=BASEURI+"pdf/"+"demo.pdf";
            try {
                ConverterProperties properties = new ConverterProperties();
                FontProvider fontProvider = new DefaultFontProvider();
                FontProgram fontProgram = FontProgramFactory.createFont(BASEURI+"font/NotoSansCJKsc-Regular.otf");
                fontProvider.addFont(fontProgram);
                properties.setFontProvider(fontProvider);

                HtmlConverter.convertToPdf(html, new FileOutputStream(pdfName),properties);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("html转化为pdf成功");


            //3.上传文件到Cos
            System.out.println("开始上传文件到cos");

            WebClient client = WebClient.create(vertx);
            File file = new File(pdfName);
            String name = file.getName();
            Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);

            URL urlObj = cosclient.generatePresignedUrl(savebucketname, name, expirationTime, HttpMethodName.PUT);
            cosclient.shutdown();
            String url = urlObj.toString();

            MultipartForm form = MultipartForm.create().binaryFileUpload("fileName", file.getName(), file.getAbsolutePath(), "application/pdf");
            client.putAbs(url).sendMultipartForm(form, ar -> {
                if (ar.succeeded()) {
                    if(ar.result().statusCode()==200){
                        System.out.println("上传文件成功。cos上的路径为："+name);
                    }else{
                        System.out.println("错误码是"+ar.result().statusCode()+"上传异常："+ar.result().statusMessage());
                    }
                } else {
                    System.out.println("上传文件失败！"+ar.cause().toString());
                }
                vertx.close();
            });
        });
    }

    static {
        getProperties();
        getCOSClient();
    }

    private static void getProperties() {
        Properties pro = new Properties();
        InputStream in = VertxPebbleTemplate.class.getClassLoader().getResourceAsStream("cos.properties");
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        secretid = pro.getProperty("SecretId");
        secretkey = pro.getProperty("SecretKey");
        region = pro.getProperty("Region");
        savebucketname = pro.getProperty("SaveBucketName");
    }

    public static void getCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(secretid, secretkey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        cosclient = new COSClient(cred, clientConfig);
    }
}
